package com.ficv.findme;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class CopyOfGpsService  extends Service {
		   
		  private static final String MiService = CopyOfGpsService.class.getSimpleName();
		  
		  LocationManager locationManager;
		  Handler handler;
		  
		  private Timer timer;
		  
		  private long cont=1;
		  private long intentos=0;
		  
		//SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
			
		  //private TimerTask updateTask = new MyTimerTask();
		  
		  private class MyTimerTask extends TimerTask {
		    @Override
		    public void run() {
		    	
		  //  	String data=prefs.getString("com.ficv.findme.data","dddd"); 
			String data=JavascriptFacade.DATA;	
		      Log.i(MiService, "Timer task doing work with data: " + data);
		      synchronized (serviceLock) {
				  
		    	  handler.post(new Runnable() { // This thread runs in the UI
	                    @Override
	                    public void run() {  Log.i(MiService, "REQUEST UPDATES: ");
	     		    	   locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
	     			                1000,          // msecond interval.
	     			                15,             //  meters.
	     			                listenerGPS);
	     		    	   
//	     		    	   locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
//	     			                1000,          // msecond interval.
//	     			                15,             //  meters.
//	     			                listenerNET);
	                    }
	                });


		    	}
		    		
		    }

			
		  };
		   
		
		  private Location lastLocation=null;
		  
		  private final LocationListener listenerGPS =  new MyLocationListener();
		  //private final LocationListener listenerNET =  new MyLocationListener();		
		  
		  
		  private class MyLocationListener implements LocationListener {

			    @Override
			    public void onLocationChanged(Location location) {

			    	if(isBetterLocation(location, lastLocation)) {

				    	try { Log.i(MiService, "LOCATION accuracy: " + location.getAccuracy());
				    		
				    		 //if(location.getAccuracy()<20 || intentos++ > 5) {
						    	  timer.cancel();
						    	  //setNewPosition(location.getLatitude(),location.getLongitude(),location.getAccuracy());
						    	 // SendPosition sp= new SendPosition(getContentResolver());
								  //sp.execute(String.valueOf(location.getLatitude()),String.valueOf(location.getLongitude()),String.valueOf(location.getAccuracy())); 
								  Log.i(MiService, "LOCATION " + location.getProvider()+ " sending: " + location.getLatitude() + "," + location.getLongitude());
						    	  
						    	  locationManager.removeUpdates(this);
						    	  cont++;
						    	  intentos=0;
						    	  timer=new Timer("gpsTimer");
						    	  timer.schedule(new MyTimerTask(), 10000L); // * cont);
						    	  lastLocation=location;
				    		 //}
				    	} catch(Throwable e) {
				    		Log.v("ERROR: ", e.getMessage());
				       
				    	}
			    	}
			    }

				@Override
				public void onProviderDisabled(String provider) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onProviderEnabled(String provider) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onStatusChanged(String provider, int status,
						Bundle extras) {
					// TODO Auto-generated method stub
					
				}
			    

		  };
		  
private final Object serviceLock = new Object();


	  
		  @Override
		  public IBinder onBind(Intent intent) {
		    // TODO Auto-generated method stub
		    return null;
		  }
		 
		/*  public void notifica() {
			  String ns = Context.NOTIFICATION_SERVICE;
	    		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
	    		
	    		int icon = R.drawable.ic_launcher;
	    		CharSequence tickerText = "Nuevo aviso de tucanalmovil";
	    		long when = System.currentTimeMillis();

	    		Notification notification = new Notification(icon, tickerText, when);
	    		
	    		Context context = getApplicationContext();
	    		CharSequence contentTitle = "Avisos de tu canal móvil";
	    		CharSequence contentText=msg;
	    		Intent notificationIntent = new Intent(this, MainActivity.class);
	    		notificationIntent.putExtra("NotificationMessage", msg);
	    		notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
	    		notification.flags |= Notification.FLAG_AUTO_CANCEL;

	    		PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);


	    		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
	    			    		

	    		mNotificationManager.notify(101, notification);

		}*/

		@Override
		  public void onCreate() {
		    super.onCreate();
		    Log.i(MiService, "Service creating");
		     
		    handler = new Handler();
		    locationManager =  (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
		    
		    timer = new Timer("gpsTimer");
		    timer.schedule(new MyTimerTask(), 1000L); //, 10 * 1000L);
		  }
		 
		  @Override
		  public void onDestroy() {
		    super.onDestroy();
		    
		    locationManager.removeUpdates(listenerGPS);
//		    locationManager.removeUpdates(listenerNET);
//		    
		    Log.i(MiService, "Service destroying");
		     
		    timer.cancel();
		    timer = null;
		  }

		  


		  
		  
	  protected void setNewPosition(double lat, double lon, float precision) {
			
				try 
				{

					//String androidId=Secure.getString(getContentResolver(), Secure.ANDROID_ID);	
					String androidId="172.30.49.27";
					Date d = new Date();
					String url = MainActivity.URL_BASE + "position?id=" + androidId + "&lat="+ lat + "&lon="+ lon + "&precision="+ precision + "&time=" + d.getTime();


					HttpHeaders requestHeaders = new HttpHeaders();
					List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
					acceptableMediaTypes.add(MediaType.APPLICATION_JSON);
					requestHeaders.setAccept(acceptableMediaTypes);
					
					// Populate the headers in an HttpEntity object to use for the request
					HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
					
					// Create a new RestTemplate instance
					RestTemplate restTemplate = new RestTemplate();
					
					// Perform the HTTP GET request
					ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
					
					// Return the list of states
					String result  = responseEntity.getBody();

					Log.v(MiService, url + ": " + result);
				} 
				catch(Exception e) 
				{
					Log.e("TAG", e.getMessage(), e);
				} 

			}   
		   
		   
private static final int TWO_MINUTES = 1000 * 60 * 2;

/** Determines whether one Location reading is better than the current Location fix
  * @param location  The new Location that you want to evaluate
  * @param currentBestLocation  The current Location fix, to which you want to compare the new one
  */
protected boolean isBetterLocation(Location location, Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return true;
    }

    // Check whether the new location fix is newer or older
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;

    // If it's been more than two minutes since the current location, use the new location
    // because the user has likely moved
    if (isSignificantlyNewer) {
        return true;
    // If the new location is more than two minutes older, it must be worse
    } else if (isSignificantlyOlder) {
        return false;
    }

    // Check whether the new location fix is more or less accurate
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

    // Check if the old and new location are from the same provider
    boolean isFromSameProvider = isSameProvider(location.getProvider(),
            currentBestLocation.getProvider());

    // Determine location quality using a combination of timeliness and accuracy
    if (isMoreAccurate) {
        return true;
    } else if (isNewer && !isLessAccurate) {
        return true;
    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
        return true;
    }
    return false;
}

/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) {
      return provider2 == null;
    }
    return provider1.equals(provider2);
}


}


